import { createRouter, createWebHistory } from 'vue-router'
import { useUserStore } from '@/stores/user'

const routes = [
    {
        path: '/login',
        name: 'Login',
        component: () => import('@/views/Login.vue'),
        meta: {
            title: '登录',
            requiresGuest: true // 只有未登录用户可以访问
        }
    },

    // 管理员路由 - 使用 AdminLayout
    {
        path: '/admin',
        component: () => import('@/layouts/AdminLayout.vue'),
        meta: {
            requiresAuth: true,
            requiresAdmin: true,
            title: '管理中心'
        },
        children: [
            {
                path: '',
                name: 'AdminDashboard',
                component: () => import('@/views/admin/Dashboard.vue'),
                meta: { title: '管理员仪表板' }
            },
            {
                path: 'service-contrib-overview',
                name: 'AdminServiceContributionOverview',
                component: () => import('@/views/admin/ServiceContributionOverview.vue'),
                meta: { title: '服务贡献总览' }
            },
            {
                path: 'service-contrib-review',
                name: 'AdminServiceContributionReview',
                component: () => import('@/views/admin/ServiceContributionReview.vue'),
                meta: { title: '服务贡献审核' }
            },
            {
                path: 'projects',
                name: 'AdminProjectManagement',
                component: () => import('@/views/admin/ProjectManagement.vue'),
                meta: { title: '项目管理' }
            },
            {
                path: 'review',
                name: 'ReviewCenter',
                component: () => import('@/views/admin/ReviewCenter.vue'),
                meta: { title: '审核中心' }
            },
            // 兼容旧链接：/admin/party-building -> /admin/party-overview
            {
                path: 'party-building',
                redirect: '/admin/party-overview'
            },
            {
                path: 'awards',
                name: 'AdminAwards',
                component: () => import('@/views/admin/Awards.vue'),
                meta: { title: '奖项总览' }
            },
            {
                path: 'award-review',
                name: 'AwardReview',
                component: () => import('@/views/admin/AwardReview.vue'),
                meta: { title: '奖项审核' }
            },
            {
                path: 'academic-overview',
                name: 'AdminAcademicOverview',
                component: () => import('@/views/admin/AcademicAchievementOverview.vue'),
                meta: { title: '学术成果总览' }
            },
            {
                path: 'academic-achievements',
                name: 'AdminAcademicAchievements',
                component: () => import('@/views/admin/AcademicAchievementReview.vue'),
                meta: { title: '学术成果审核' }
            },
            {
                path: 'course-hours-overview',
                name: 'CourseHoursOverview',
                component: () => import('@/views/admin/CourseHoursOverview.vue'),
                meta: { title: '教学课时总览' }
            },
            {
                path: 'activity-overview',
                name: 'AdminActivityOverview',
                component: () => import('@/views/admin/ActivityOverview.vue'),
                meta: { title: '学术活动总览' }
            },
            {
                path: 'activities',
                name: 'AdminActivities',
                component: () => import('@/views/admin/ActivityManagement.vue'),
                meta: { title: '学术活动审核' }
            },
            {
                path: 'student-guidance-overview',
                name: 'AdminStudentGuidanceOverview',
                component: () => import('@/views/admin/StudentGuidanceOverview.vue'),
                meta: { title: '人才培养总览' }
            },
            {
                path: 'student-guidance',
                name: 'AdminStudentGuidance',
                component: () => import('@/views/admin/StudentGuidanceManagement.vue'),
                meta: { title: '人才培养审核' }
            },
            {
                path: 'academic-positions',
                name: 'AdminAcademicPositions',
                component: () => import('@/views/admin/AcademicPositionsManagement.vue'),
                meta: { title: '学术兼职管理' }
            },
            {
                path: 'social-services',
                name: 'AdminSocialServices',
                component: () => import('@/views/admin/SocialServicesManagement.vue'),
                meta: { title: '社会服务管理' }
            },
            {
                path: 'influence-stats',
                name: 'AdminInfluenceStats',
                component: () => import('@/views/admin/AcademicSocialStats.vue'),
                meta: { title: '社会影响力统计' }
            },
            {
                path: 'textbooks',
                name: 'AdminTextbooks',
                component: () => import('@/views/admin/TextbooksManagement.vue'),
                meta: { title: '教材/专著管理' }
            },
            // 新增：人才计划/荣誉称号
            {
                path: 'honors',
                name: 'AdminHonors',
                component: () => import('@/views/admin/Honors.vue'),
                meta: { title: '人才与荣誉' }
            },
            {
                path: 'party-overview',
                name: 'AdminPartyOverview',
                component: () => import('@/views/admin/PartyOverview.vue'),
                meta: { title: '党建总览' }
            },
            {
                path: 'party-review',
                name: 'AdminPartyReview',
                component: () => import('@/views/admin/PartyReview.vue'),
                meta: { title: '党建审核' }
            }
        ]
    },

    // 教职工路由 - 使用 StaffLayout
    {
        path: '/staff',
        component: () => import('@/layouts/StaffLayout.vue'),
        meta: {
            requiresAuth: true,
            title: '教职工工作台'
        },
        children: [
            {
                path: '',
                name: 'StaffDashboard',
                component: () => import('@/views/staff/Dashboard.vue'),
                meta: { title: '工作台' }
            },

            {
                path: 'teaching-projects',
                name: 'TeachingProjects',
                component: () => import('@/views/staff/TeachingProjects.vue'),
                meta: { title: '教学项目' }
            },
            {
                path: 'research-projects',
                name: 'ResearchProjects',
                component: () => import('@/views/staff/ResearchProjects.vue'),
                meta: { title: '科研项目' }
            },
            {
                path: 'awards',
                name: 'Awards',
                component: () => import('@/views/staff/Awards.vue'),
                meta: { title: '获奖情况' }
            },
            {
                path: 'honors',
                name: 'StaffHonors',
                component: () => import('@/views/staff/Honors.vue'),
                meta: { title: '人才与荣誉' }
            },
            {
                path: 'academic-achievements',
                name: 'AcademicAchievements',
                component: () => import('@/views/staff/AcademicAchievements.vue'),
                meta: { title: '学术成果' }
            },
            {
                path: 'course-hours',
                name: 'CourseHours',
                component: () => import('@/views/staff/CourseHours.vue'),
                meta: { title: '课时统计' }
            },
            {
                path: 'activities',
                name: 'Activities',
                component: () => import('@/views/staff/Activities.vue'),
                meta: { title: '活动记录' }
            },
            {
                path: 'party-building',
                name: 'PartyBuilding',
                component: () => import('@/views/staff/PartyBuilding.vue'),
                meta: { title: '党建工作' }
            },
            {
                path: 'student-guidance',
                name: 'StaffStudentGuidance',
                component: () => import('@/views/staff/StudentGuidance.vue'),
                meta: { title: '指导学生' }
            },
            {
                path: 'academic-positions',
                name: 'StaffAcademicPositions',
                component: () => import('@/views/staff/AcademicPositions.vue'),
                meta: { title: '学术兼职' }
            },
            {
                path: 'social-services',
                name: 'StaffSocialServices',
                component: () => import('@/views/staff/SocialServices.vue'),
                meta: { title: '社会服务' }
            },
            {
                path: 'textbooks',
                name: 'StaffTextbooks',
                component: () => import('@/views/staff/Textbooks.vue'),
                meta: { title: '教材/专著' }
            }
            ,{
                path: 'service-contribution',
                name: 'StaffServiceContribution',
                component: () => import('@/views/staff/ServiceContribution.vue'),
                meta: { title: '服务贡献' }
            }
        ]
    },

    // 根路径重定向 - 延迟到路由守卫中处理
    {
        path: '/',
        name: 'Home',
        redirect: '/login' // 默认重定向到登录页，具体逻辑在路由守卫中处理
    },

    // 兼容旧路由的重定向
    {
        path: '/teaching-projects',
        redirect: '/staff/teaching-projects'
    },
    {
        path: '/awards',
        redirect: '/staff/awards'
    },
    {
        path: '/honors',
        redirect: '/staff/honors'
    },
    {
        path: '/audit',
        redirect: '/admin/review'
    },

    // 404 页面 - 放在最后
    {
        path: '/:pathMatch(.*)*',
        name: 'NotFound',
        component: () => import('@/views/NotFound.vue'),
        meta: { title: '页面未找到' }
    }
]

const router = createRouter({
    history: createWebHistory(),
    routes,
    // 滚动行为
    scrollBehavior(to, from, savedPosition) {
        if (savedPosition) {
            return savedPosition
        } else {
            return { top: 0 }
        }
    }
})

// 路由守卫
router.beforeEach(async (to, from, next) => {
    // 获取用户 store，这里需要确保 store 已经初始化
    let userStore
    try {
        userStore = useUserStore()
    } catch (error) {
        console.error('获取用户store失败:', error)
        next('/login')
        return
    }

    console.log('路由守卫:', {
        to: to.path,
        from: from.path,
        userStatus: {
            isLoggedIn: userStore.isLoggedIn,
            isAdmin: userStore.isAdmin,
            userName: userStore.userName
        }
    })

    // 设置页面标题
    if (to.meta.title) {
        document.title = `${to.meta.title} - 教学管理系统`
    }

    // 处理根路径的重定向逻辑
    if (to.path === '/' && userStore.isLoggedIn) {
        const redirectPath = userStore.isAdmin ? '/admin' : '/staff'
        next(redirectPath)
        return
    }

    // 如果去登录页且已登录，重定向到对应的主页
    if (to.meta.requiresGuest && userStore.isLoggedIn) {
        const redirectPath = userStore.isAdmin ? '/admin' : '/staff'
        next(redirectPath)
        return
    }

    // 检查是否需要登录
    if (to.meta.requiresAuth && !userStore.isLoggedIn) {
        next({
            path: '/login',
            query: { redirect: to.fullPath } // 保存重定向路径
        })
        return
    }

    // 检查是否需要管理员权限
    if (to.meta.requiresAdmin && !userStore.isAdmin) {
        console.warn('用户尝试访问管理员页面但权限不足')
        next('/staff')
        return
    }

    // 确保教职工不能访问管理员页面
    if (to.path.startsWith('/admin') && userStore.isLoggedIn && !userStore.isAdmin) {
        console.warn('教职工用户尝试访问管理员页面')
        next('/staff')
        return
    }

    // 确保管理员不会意外进入教职工页面（除非明确导航）
    if (to.path.startsWith('/staff') && userStore.isAdmin && from.path !== '/login') {
        // 如果管理员明确点击导航到教职工页面，允许访问
        // 这里可以根据实际需求调整逻辑
    }

    next()
})

// 路由错误处理
router.onError((error) => {
    console.error('路由错误:', error)
})

// 后置路由守卫 - 可以用于日志记录等
router.afterEach((to, from) => {
    console.log(`路由跳转: ${from.path} -> ${to.path}`)
})

export default router